
/**
 * PromptSidebar - 提示词管理工具
 * Copyright (C) 2025
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 */

import type { VariableInput } from '@/types';

/**
 * 从文本中提取变量
 * 支持 ${variable} 格式
 */
export function extractVariables(text: string): string[] {
  const regex = /\$\{([^}]+)\}/g;
  const variables: string[] = [];
  let match;
  
  while ((match = regex.exec(text)) !== null) {
    const variable = match[1].trim();
    if (variable && !variables.includes(variable)) {
      variables.push(variable);
    }
  }
  
  return variables;
}

/**
 * 替换文本中的变量
 */
export function replaceVariables(text: string, variables: VariableInput[]): string {
  let result = text;
  
  variables.forEach(variable => {
    const regex = new RegExp(`\\$\\{${variable.name}\\}`, 'g');
    result = result.replace(regex, variable.value);
  });
  
  return result;
}

/**
 * 验证变量输入
 */
export function validateVariableInputs(variables: VariableInput[]): boolean {
  return variables.every(variable => variable.value.trim() !== '');
}

/**
 * 创建变量输入对象
 */
export function createVariableInputs(variableNames: string[]): VariableInput[] {
  return variableNames.map(name => ({
    name,
    value: '',
    placeholder: `请输入${name}`
  }));
}